package com.clouddot.baipai.util.FtpUtil;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.FileWriter;
import java.io.InputStream;

public class AnalyzeXMLUtil {
    public static XMLBean parseXML(InputStream in) {
        XMLBean udataInfo = null;
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(in, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        udataInfo = new XMLBean();
                        break;
                    case XmlPullParser.START_TAG:
                        if (parser.getName().equals("Version")) {
                            udataInfo.setVersion(parser.nextText() + "");
                        } else if (parser.getName().equals("Url")) {
                            udataInfo.setUrl(parser.nextText());
                        } else if (parser.getName().equals("Data")) {
                            udataInfo.setData(parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return udataInfo;
    }

    public static String modifyXml(String xmlPath, XMLBean xmlBean) {
        // 创建文件工厂实例
        XmlSerializer serializer = Xml.newSerializer();
        FileWriter writer = null;
        try {
            writer = new FileWriter(xmlPath, false);
            serializer.setOutput(writer);
            serializer.startDocument("UTF-8", true);
            //第一个参数为命名空间,如果不使用命名空间,可以设置为null
            serializer.startTag("", "root");
            serializer.startTag("", "Version");
            serializer.text(xmlBean.getVersion());
            serializer.endTag("", "Version");
            serializer.startTag("", "Url");
            serializer.text(xmlBean.getUrl());
            serializer.endTag("", "Url");
            serializer.startTag("", "Data");
            serializer.text(xmlBean.getData());
            serializer.endTag("", "Data");
            serializer.endTag("", "root");
            serializer.endDocument();
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlPath;
    }
}
